package org.megha.blog.example.selenium;

import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * A Junit4 test to use webdriver to search for "google" on yahoo.com.
 * 
 * @author megha birmiwal
 */
public class WebdriverYahooTest {

	private static FirefoxDriver driver;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		driver = new FirefoxDriver();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		driver.close();
	}

	@Test
	public void testYahooSearch() {
		driver.get("http://www.yahoo.com/");
		WebElement searchBox = driver.findElement(By.name("p"));
		searchBox.sendKeys("google");
		WebElement submit = driver.findElement(By.id("search-submit"));
		submit.click();

		waitForPresence(driver, By.id("main"), 5000);
		WebElement resultsElement = driver.findElement(By.id("main"));
		Assert.assertTrue("google.com not found in search results",
				resultsElement.getText().contains("google.com"));
	}

	private boolean waitForPresence(WebDriver driver, By spec, int timeout) {
		long endTime = System.currentTimeMillis() + timeout;
		while (System.currentTimeMillis() < endTime) {
			List<WebElement> elements = driver.findElements(spec);
			if (!elements.isEmpty()) {
				return true;
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
		}
		return false;
	}
}
